<template>
  <el-card shadow="never">
    <template #header>
      <div class="flex justify-between">
        <span class="text-sm">订单统计</span>
        <div>
          <el-check-tag
            :disabled="isloading"
            v-for="(item, index) in options"
            :key="index"
            :checked="current == item.value"
            style="margin-right: 8px"
            @click="handleChoose(item.value)"
            >{{ item.text }}
          </el-check-tag>
        </div>
      </div>
    </template>
    <div ref="chart" id="chart" style="width: 100%; height: 300px"></div>
  </el-card>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import { getStatistics3 } from '@/api/index.js'
import { useResizeObserver } from '@vueuse/core'
import { fa } from 'element-plus/es/locales.mjs'

// tags默认选中
const current = ref('week')

// 处理tags内容
const options = [
  {
    text: '近1个月',
    value: 'month'
  },
  {
    text: '近1周',
    value: 'week'
  },
  {
    text: '近24小时',
    value: 'hour'
  }
]

// 处理tags选中
const isloading = ref(false)
const handleChoose = type => {
  if (!isloading.value) {
    current.value = type
    getData() // 重新获取数据
    isloading.value = true // 开始禁用
  }
}

var myChart = null
onMounted(() => {
  var chartDom = document.getElementById('chart')
  if (chartDom) {
    // 如果chartDom存在，才调用echarts
    myChart = echarts.init(chartDom)
    getData()
  }
})

function getData () {
  let option = {
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        data: [],
        type: 'bar',
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        }
      }
    ]
  }
  // 添加loading动画
  myChart.showLoading()
  // 调用接口
  getStatistics3(current.value)
    .then(res => {
      option.xAxis.data = res.x
      option.series[0].data = res.y
      myChart.setOption(option)
    })
    .finally(() => {
      setTimeout(() => {
        // 使用了定时器，让动画加载久一点
        myChart.hideLoading()
        isloading.value = false // 取消禁用
      }, 1000)
    })
  // option && myChart.setOption(option)
}

// 解决图表白屏问题
onBeforeUnmount(() => {
  if (myChart) echarts.dispose(myChart)
})

// 随屏幕变化图表大小
const chart = ref(null)
useResizeObserver(chart, entries => {
  myChart.resize()
})
</script>
